import { Router } from "express";
import { authenticateToken } from "../middleware/auth";
import { HospitalSite, EquipmentUsage, IHospitalSite, IEquipmentUsage } from "../models/mongodb-schemas";

const router = Router();

// GET /v1/hospital-site - 获取所有医院站点
router.get("/", async (req, res) => {
  try {
    const { 
      status,
      city,
      province,
      page = 1, 
      limit = 50 
    } = req.query;

    // 构建查询条件
    const filter: any = {};
    
    if (status) {
      filter.status = status;
    }
    
    if (city) {
      filter.city = city;
    }
    
    if (province) {
      filter.province = province;
    }

    // 分页
    const pageNum = parseInt(page as string);
    const limitNum = parseInt(limit as string);
    const skip = (pageNum - 1) * limitNum;

    // 执行查询
    const [sites, total] = await Promise.all([
      HospitalSite.find(filter)
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(limitNum)
        .lean(),
      HospitalSite.countDocuments(filter)
    ]);

    res.json({
      success: true,
      data: {
        sites,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total,
          pages: Math.ceil(total / limitNum)
        }
      }
    });

  } catch (error) {
    console.error('获取医院站点失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医院站点失败',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

// GET /v1/hospital-site/nearby - 根据坐标获取附近的医院站点
router.get("/nearby", async (req, res) => {
  try {
    const { 
      longitude, 
      latitude, 
      maxDistance = 10000,  // 默认10公里
      limit = 10 
    } = req.query;

    if (!longitude || !latitude) {
      return res.status(400).json({
        success: false,
        message: '需要提供经纬度坐标'
      });
    }

    const sites = await HospitalSite.find({
      status: 'active',
      coordinates: {
        $near: {
          $geometry: {
            type: 'Point',
            coordinates: [parseFloat(longitude as string), parseFloat(latitude as string)]
          },
          $maxDistance: parseInt(maxDistance as string)
        }
      }
    })
    .limit(parseInt(limit as string))
    .lean();

    res.json({
      success: true,
      data: sites
    });

  } catch (error) {
    console.error('获取附近医院站点失败:', error);
    res.status(500).json({
      success: false,
      message: '获取附近医院站点失败'
    });
  }
});

// GET /v1/hospital-site/:id - 获取医院站点详情
router.get("/:id", async (req, res) => {
  try {
    const siteId = req.params.id;
    const site = await HospitalSite.findOne({ siteId }).lean();
    
    if (!site) {
      return res.status(404).json({
        success: false,
        message: '医院站点不存在'
      });
    }

    // 获取该站点的设备使用率信息
    const equipmentUsage = await EquipmentUsage.find({ siteId })
      .sort({ lastUpdated: -1 })
      .lean();

    res.json({
      success: true,
      data: {
        ...site,
        equipmentUsage
      }
    });

  } catch (error) {
    console.error('获取医院站点详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医院站点详情失败'
    });
  }
});

// POST /v1/hospital-site - 创建医院站点 (需要管理员权限)
router.post("/", authenticateToken, async (req, res) => {
  try {
    const siteData = {
      siteId: `site_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      ...req.body,
      createdAt: new Date(),
      updatedAt: new Date()
    };

    const site = new HospitalSite(siteData);
    await site.save();

    res.status(201).json({
      success: true,
      data: site,
      message: '医院站点创建成功'
    });

  } catch (error) {
    console.error('创建医院站点失败:', error);
    res.status(500).json({
      success: false,
      message: '创建医院站点失败',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

// PUT /v1/hospital-site/:id - 更新医院站点 (需要管理员权限)
router.put("/:id", authenticateToken, async (req, res) => {
  try {
    const siteId = req.params.id;
    const updateData = {
      ...req.body,
      updatedAt: new Date()
    };

    const site = await HospitalSite.findOneAndUpdate(
      { siteId },
      updateData,
      { new: true, runValidators: true }
    );

    if (!site) {
      return res.status(404).json({
        success: false,
        message: '医院站点不存在'
      });
    }

    res.json({
      success: true,
      data: site,
      message: '医院站点更新成功'
    });

  } catch (error) {
    console.error('更新医院站点失败:', error);
    res.status(500).json({
      success: false,
      message: '更新医院站点失败'
    });
  }
});

// DELETE /v1/hospital-site/:id - 删除医院站点 (需要管理员权限)
router.delete("/:id", authenticateToken, async (req, res) => {
  try {
    const siteId = req.params.id;
    
    // 删除医院站点
    const site = await HospitalSite.findOneAndDelete({ siteId });

    if (!site) {
      return res.status(404).json({
        success: false,
        message: '医院站点不存在'
      });
    }

    // 同时删除相关的设备使用率数据
    await EquipmentUsage.deleteMany({ siteId });

    res.json({
      success: true,
      message: '医院站点删除成功'
    });

  } catch (error) {
    console.error('删除医院站点失败:', error);
    res.status(500).json({
      success: false,
      message: '删除医院站点失败'
    });
  }
});

// GET /v1/hospital-site/:id/equipment - 获取医院站点设备使用率
router.get("/:id/equipment", async (req, res) => {
  try {
    const siteId = req.params.id;
    
    // 验证站点存在
    const site = await HospitalSite.findOne({ siteId });
    if (!site) {
      return res.status(404).json({
        success: false,
        message: '医院站点不存在'
      });
    }

    // 获取设备使用率数据
    const equipmentUsage = await EquipmentUsage.find({ siteId })
      .sort({ lastUpdated: -1 })
      .lean();

    // 按设备类型分组统计
    const typeStats = await EquipmentUsage.aggregate([
      { $match: { siteId } },
      {
        $group: {
          _id: '$equipmentType',
          totalCapacity: { $sum: '$totalCapacity' },
          totalUsage: { $sum: '$currentUsage' },
          avgUsageRate: { $avg: '$usageRate' },
          count: { $sum: 1 },
          normalCount: {
            $sum: { $cond: [{ $eq: ['$status', 'normal'] }, 1, 0] }
          },
          warningCount: {
            $sum: { $cond: [{ $eq: ['$status', 'warning'] }, 1, 0] }
          },
          criticalCount: {
            $sum: { $cond: [{ $eq: ['$status', 'critical'] }, 1, 0] }
          }
        }
      },
      { $sort: { avgUsageRate: -1 } }
    ]);

    // 总体统计
    const overallStats = await EquipmentUsage.aggregate([
      { $match: { siteId } },
      {
        $group: {
          _id: null,
          totalEquipment: { $sum: 1 },
          avgUsageRate: { $avg: '$usageRate' },
          totalCapacity: { $sum: '$totalCapacity' },
          totalUsage: { $sum: '$currentUsage' }
        }
      }
    ]);

    res.json({
      success: true,
      data: {
        equipment: equipmentUsage,
        typeStats,
        overallStats: overallStats[0] || {
          totalEquipment: 0,
          avgUsageRate: 0,
          totalCapacity: 0,
          totalUsage: 0
        }
      }
    });

  } catch (error) {
    console.error('获取设备使用率失败:', error);
    res.status(500).json({
      success: false,
      message: '获取设备使用率失败'
    });
  }
});

// POST /v1/hospital-site/:id/equipment - 更新设备使用率数据
router.post("/:id/equipment", authenticateToken, async (req, res) => {
  try {
    const siteId = req.params.id;
    const equipmentData = req.body;

    // 验证站点存在
    const site = await HospitalSite.findOne({ siteId });
    if (!site) {
      return res.status(404).json({
        success: false,
        message: '医院站点不存在'
      });
    }

    // 批量处理设备数据
    const equipmentList = Array.isArray(equipmentData) ? equipmentData : [equipmentData];
    const results = [];

    for (const equipment of equipmentList) {
      const usageId = equipment.usageId || `usage_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      // 计算使用率和状态
      const usageRate = equipment.totalCapacity > 0 
        ? Math.round((equipment.currentUsage / equipment.totalCapacity) * 100)
        : 0;
      
      let status = 'normal';
      if (usageRate >= 90) status = 'critical';
      else if (usageRate >= 75) status = 'warning';
      
      const equipmentUsage = await EquipmentUsage.findOneAndUpdate(
        { usageId },
        {
          usageId,
          siteId,
          ...equipment,
          usageRate,
          status,
          lastUpdated: new Date()
        },
        { 
          new: true, 
          upsert: true, 
          runValidators: true 
        }
      );

      results.push(equipmentUsage);
    }

    res.json({
      success: true,
      data: results,
      message: '设备使用率更新成功'
    });

  } catch (error) {
    console.error('更新设备使用率失败:', error);
    res.status(500).json({
      success: false,
      message: '更新设备使用率失败'
    });
  }
});

export default router;